package it.CookBook;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainGridViewActivity extends Activity {

	ArrayList<NodeBean> listFiles = new ArrayList<NodeBean>();
	ArrayList<File> filteredList = new ArrayList<File>();
	int itemSelectedFromResult;
	
	GridView gridView;
	String cookBookRoot = "/mnt/sdcard/Ricettario";
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	    
	    setContentView(R.layout.maingridview);

	    gridView = (GridView) findViewById(R.id.gridview);
	    gridView.setAdapter(new ImageAdapter(this,cookBookRoot));
	    gridView.requestFocus();
	    
	    gridView.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	            Animation grow = AnimationUtils.loadAnimation(MainGridViewActivity.this, R.anim.grow);
	            v.startAnimation(grow);
	        	NodeBean nodeBean = ((NodeBean)listFiles.get(position));
	        	if (nodeBean.getFile().getAbsolutePath().equals(cookBookRoot)){
	        		Toast.makeText(MainGridViewActivity.this, "Non puoi andare oltre!!!", Toast.LENGTH_SHORT).show();
	        		return;
	        	}
	        	
	        	if (((NodeBean)listFiles.get(position)).getFile().getName().contains(".jpg")){
		            Intent intent = new Intent(MainGridViewActivity.this, ShowImage.class);
		            Bundle b = new Bundle();
		            b.putString("imageName", nodeBean.getFile().getAbsolutePath()); //Your id
		            b.putInt("imagePosition",-1); 
		            intent.putExtras(b);
		            startActivity(intent);
	    		}
	        	else{
	        		if (nodeBean.getName() == "UP")
	        			nodeBean.setFile(nodeBean.getFile().getParentFile());
	        		
		    	    gridView = (GridView) findViewById(R.id.gridview);
		    	    gridView.setAdapter(new ImageAdapter(parent.getContext(),nodeBean.getFile().getAbsolutePath()));
		    	    gridView.invalidate();
	        	}
	            Toast.makeText(MainGridViewActivity.this, "" + position, Toast.LENGTH_SHORT).show();
	        }
	    });
	    
	}
	
	public void premutoBottone(View v){
		startActivity(new Intent(getApplicationContext(), MultiTouchVisualizerActivity.class));
	}
	
	public void keepDisplayOn(View v){
	}

	public void findCookRecipe(View v){
		//startActivity(new Intent(getApplicationContext(), MultiTouchVisualizerActivity.class));
		filteredList.clear();
		EditText findTxt = (EditText) findViewById(R.id.ricerca);
		final String toFind = findTxt.getText().toString();
		if (toFind.length() == 0)
			 return;
		
		FilenameFilter filenameFilter = new FilenameFilter() {
			String toFind1 = toFind; 
			public boolean accept(File dir, String name) {
				
				Log.d("CookBook", name + "," + this.toFind1 + ", "+ name.endsWith(".jpg") + "," + name.contains(this.toFind1));
				if (dir.isDirectory())
					return true;
				
				if (name.endsWith(".jpg") && name.contains(this.toFind1))
					return true;
				
				return false;
			}
		};		
		
		CookBookExplorer.findFiles(new File(cookBookRoot), findTxt.getText().toString(), filteredList);
		filteredList.size();
		ArrayList<String> tempItemFound = new ArrayList<String>();
		final ArrayList<String> listOfResults = new ArrayList<String>();
		for (File file : filteredList) {
			String name = file.getName().toUpperCase();
			tempItemFound.add(name.substring(0,name.lastIndexOf(".JPG") == -1 ? name.length() : name.lastIndexOf(".JPG")));
			listOfResults.add(file.getAbsolutePath());
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Quale cercavi?");
		builder.setItems(tempItemFound.toArray(new String[0]), new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		         // Do something with the selection
		    	itemSelectedFromResult = item;
	            Intent intent = new Intent(MainGridViewActivity.this, ShowImage.class);
	            Bundle b = new Bundle();
	            b.putString("imageName", ((File)filteredList.get(item)).getAbsolutePath());
	            b.putBoolean("showMoreResult", filteredList.size() > 1 ? true : false);
	    		b.putInt("imagePosition", item);
	    		b.putStringArrayList("listOfResults",listOfResults);
	            intent.putExtras(b);
	            startActivity(intent);
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
		//startActivity(new Intent(getApplicationContext(), CookBookActivity.class));
	}
	

	public class ImageAdapter extends BaseAdapter {
	    int mGalleryItemBackground;
	    private Context mContext;

	    public ImageAdapter(Context c, String root) {
	        mContext = c;
//	        TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
//	        mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
//	        attr.recycle();
	        File directory = new File(root);
	        listFiles.clear();
			CookBookExplorer.createNodes(directory, new ArrayList<String>(), listFiles, root.equals(cookBookRoot));	        
	    }

	    public int getCount() {
	        return listFiles.size();
	    }

	    public Object getItem(int position) {
	        return position;
	    }

	    public long getItemId(int position) {
	        return position;
	    }

	    public View getView(int position, View convertView, ViewGroup parent) {

            View cell = convertView;

	        if (cell == null) {  // if it's not recycled, initialize some attributes
                LayoutInflater li = getLayoutInflater();
                cell = li.inflate(R.layout.cell, null);
            }
	        
            TextView tv = (TextView)cell.findViewById(R.id.icon_text);
            tv.setText(((NodeBean)listFiles.get(position)).getName());
            tv.setTextColor(Color.WHITE);
            
            ImageView imageView = (ImageView)cell.findViewById(R.id.icon_image);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setPadding(8, 8, 8, 8);
            
            if (((NodeBean)listFiles.get(position)).getFile().isDirectory()){
            	imageView.setBackgroundResource(mGalleryItemBackground);
            	
            	Bitmap viewBitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
            	Canvas canvas = new Canvas(viewBitmap);
            	
            	Paint paintRect = new Paint();
            	paintRect.setColor(Color.rgb(178, 34, 34));
            	paintRect.setStyle(Style.FILL_AND_STROKE);
            	canvas.drawRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), 12f, 12f, paintRect);
            	
            	Paint paint = new Paint(); 
            	paint.setColor(Color.BLACK); 
            	paint.setTextSize(15); 
            	ArrayList<String> splittedString = new ArrayList<String>();
            	splittedString = StringUtil.splitStrint(((NodeBean)listFiles.get(position)).getFile().getName(), paint, canvas.getWidth());
            	if (((NodeBean)listFiles.get(position)).getName() == "UP"){
            		int textOrdinatePosition = 20;
            		for (String string : splittedString) {
            			canvas.drawText(string, 3, textOrdinatePosition, paint);
            			textOrdinatePosition += 20;
					}
            		canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.up_folder_image), 50, 50, paintRect);
            	}
            	else{
            		int textOrdinatePosition = 100;
            		for (String string : splittedString) {
            			canvas.drawText(string, 3, textOrdinatePosition, paint);
            			textOrdinatePosition += 20;
					}
            	}
            	
            	imageView.setImageBitmap(viewBitmap);
            }
            else{
            	BitmapFactory.Options options = new BitmapFactory.Options();
            	options.inTempStorage = new byte[16*1024];
            	options.inSampleSize = 16;
            	Bitmap bmp = BitmapFactory.decodeFile(((NodeBean)listFiles.get(position)).getFile().getAbsolutePath(), options);
            	imageView.setImageBitmap(bmp);
            }

			
	        return cell;
	    }
	}
}
